import React from 'react';
import './index.less'
import { Layout, Menu, Breadcrumb, Dropdown, Avatar } from 'antd';
import { Link, Route, Switch, withRouter } from "react-router-dom";
import { menuRoutes, menuRouteList, outRoutes, allRoutes } from '../router'
import logo from '../assets/image/logo.svg'
import { MenuUnfoldOutlined, MenuFoldOutlined, DownOutlined, UserOutlined, LogoutOutlined, SettingOutlined } from '@ant-design/icons';
import { getAllParent, setWaterMark } from '../js/utils'

const { Header, Sider, Content } = Layout;
class Root extends React.Component {
    path = () => this.props.location.pathname
    state = {
        collapsed: false,
        selectedKeys: [],
        defaultOpenKeys: getAllParent(menuRoutes, 'path', this.path()).map(item => item.path)
    }
    componentDidMount() {
        const path = this.path()
        if (path === '/login') {
            return
        }
        if (path) {
            this.setState({
                selectedKeys: [path]
            });
        } else {
            history.replaceState(null, '', '/#/home')
        }
        window.addEventListener('popstate', this.popStateHandler, false);
    }
    componentWillUnmount() {
        window.removeEventListener('popstate', this.popStateHandler, false);
    }
    popStateHandler = () => {
        setTimeout(() => {
            const { selectedKeys } = this.state
            const path = this.path()
            if (path !== selectedKeys[0]) {
                this.handleClick({ key: path })
            }
        }, 0);
    }
    handleClick = ({ key }) => {
        this.setState({
            selectedKeys: [key]
        });
    }
    getCurrentName = (path) => {
        if (path === '/home') {
            return ''
        }
        const item = menuRouteList.find(item => path === item.path)
        return item ? item.title : ''
    }
    renderMenu = (item) => {
        return item.children && item.children.length ? this.renderSubMenu(item) : this.renderMenuItem(item)
    }
    renderMenuItem = ({ path, icon, title }) => {
        return (
            <Menu.Item key={path} icon={icon}>
                <Link to={path}>{title}</Link>
            </Menu.Item>
        )
    }
    renderSubMenu = ({ path, icon, title, children }) => {
        return (
            <Menu.SubMenu key={path} icon={icon} title={title}>
                {
                    children && children.map(item => this.renderMenu(item))
                }
            </Menu.SubMenu>
        )
    }
    handleToHome = () => {
        this.handleClick({ key: '/home' })
    }
    toggle = () => {
        this.setState({
            collapsed: !this.state.collapsed
        });
    };
    handleMenuClick = ({ key }) => {
        if (key === 'loginOut') {
            localStorage.clear()
            this.props.history.push('/login')
        }
    }
    render() {
        const { collapsed, selectedKeys, defaultOpenKeys } = this.state
        const path = this.path()
        const isLogin = path === '/login'
        setWaterMark(isLogin ? 0 : 0.1)
        const noError = allRoutes.some(item => path === item.path)
        if (!noError) {
            this.props.history.push('/404')
        }
        const menu = (
            <Menu onClick={this.handleMenuClick}>
                <Menu.Item key="personCenter">
                    <Link to="/404"><UserOutlined />个人中心</Link>
                </Menu.Item>
                <Menu.Item key="personSet">
                    <Link to="/404"><SettingOutlined />个人设置</Link>
                </Menu.Item>
                <Menu.Divider />
                <Menu.Item key="loginOut">
                    <LogoutOutlined />退出登录
                </Menu.Item>
            </Menu>
        );
        return (
            <>
                {
                    isLogin ? <Switch>{outRoutes.map(item => <Route exact key={item.path} path={item.path} component={item.component} />)}</Switch> : <Layout className="index-page">
                        <Sider trigger={null} collapsible collapsed={collapsed}>
                            <div className="logo">
                                <img src={logo} alt="logo" />
                                {!collapsed ? <h1>Ant Design Pro</h1> : ''}
                            </div>
                            <Menu theme="dark" mode="inline" selectedKeys={selectedKeys} defaultOpenKeys={defaultOpenKeys} onClick={this.handleClick}>
                                {
                                    menuRoutes.map(item => !item.hide && this.renderMenu(item))
                                }
                            </Menu>
                        </Sider>
                        <Layout className="site-layout">
                            <Header className="layout-header">
                                <span className="trigger" onClick={this.toggle}>{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}</span>
                                <span className="user-info">
                                    <Dropdown overlay={menu} trigger={['click']} placement="bottomRight" arrow>
                                        <a className="ant-dropdown-link" onClick={e => e.preventDefault()}>
                                            <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" /> admin <DownOutlined />
                                        </a>
                                    </Dropdown>
                                </span>
                            </Header>
                            <Content className="layout-content">
                                <Breadcrumb>
                                    <Breadcrumb.Item onClick={this.handleToHome}>
                                        <Link to="/home">主页</Link>
                                    </Breadcrumb.Item>
                                    <Breadcrumb.Item>{this.getCurrentName(selectedKeys)}</Breadcrumb.Item>
                                </Breadcrumb>
                                <div className="main-page">
                                    <Switch>
                                        {menuRouteList.map(item => <Route exact key={item.path} path={item.path} component={item.component} />)}
                                    </Switch>
                                </div>
                            </Content>
                        </Layout>
                    </Layout>
                }
            </>
        );
    }
}
export default withRouter(Root)
